package main

import (
	"context"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"github.com/ztx/payment_project/common/config"
	"github.com/ztx/payment_project/common/discovery"
	"github.com/ztx/payment_project/common/genproto/stockpd"
	"github.com/ztx/payment_project/common/logging"
	"github.com/ztx/payment_project/common/server"
	"github.com/ztx/payment_project/stock/ports"
	"github.com/ztx/payment_project/stock/service"
	"google.golang.org/grpc"
	"log"
)

func init() {
	logging.Ini()
	if err := config.NewViperConfig(); err != nil { //导入配置文件
		log.Fatal(err)
	}
}

func main() {
	serviceName := viper.GetString("stock.service-name")
	serverType := viper.GetString("stock.server-to-run")

	logrus.Info(serviceName, serverType)
	ctx, cancel := context.WithCancel(context.Background()) //注意cancel用法
	defer cancel()

	application := service.NewApplication(ctx)

	deregisterFn, err := discovery.RegisterToConsul(ctx, serviceName)
	if err != nil {
		logrus.Fatal(err)
	}
	defer func() {
		_ = deregisterFn()
	}()

	log.Printf("Starting:%s", serverType)
	switch serverType {
	case "grpc": //grpc 形式的
		server.RunGRPCServer(serviceName, func(server *grpc.Server) {
			svc := ports.NewGRPCServer(application)
			stockpd.RegisterStockServiceServer(server, svc)
		})
	case "http": //http形式的
		//TODO http-server
	default:
		panic("unexpected server type")
	}
}
